/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> ret;
        if (!root) {
            return ret;
        }

        deque<TreeNode *> stack;
        TreeNode *node = root;
        TreeNode *pre = NULL;

        while(node || stack.size() > 0) {

            while(node) {
                stack.push_back(node);
                node = node->left;
            }

            if(stack.size() > 0) {
                node = stack.back();
                if (node->right && node->right != pre) {
                    node = node->right;
                } else {
                    ret.push_back(node->val);
                    stack.pop_back();
                    pre = node;
                    node = NULL;
                }
            }
        }
        return ret;
    }
};
